<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/blog/","images":"/blog/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/blog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="[TOC] Spring 定时任务详解（@Scheduled注解） initialDelay :初次执行任务之前需要等待的时间  123@Scheduled(initialDelay &#x3D;5000)public void doSomething() &amp;#123;&amp;#125; fixedDelay:每次执行任务之后间隔多久再次执行该任务。(项目启动时，会立即执行任务。可以配合initialDelay一">
<meta property="og:type" content="article">
<meta property="og:title" content="spring定时任务详解（@Scheduled注解）">
<meta property="og:url" content="http://littlefxc.github.io/2019/07/03/spring%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E8%AF%A6%E8%A7%A3%EF%BC%88-Scheduled%E6%B3%A8%E8%A7%A3%EF%BC%89/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="[TOC] Spring 定时任务详解（@Scheduled注解） initialDelay :初次执行任务之前需要等待的时间  123@Scheduled(initialDelay &#x3D;5000)public void doSomething() &amp;#123;&amp;#125; fixedDelay:每次执行任务之后间隔多久再次执行该任务。(项目启动时，会立即执行任务。可以配合initialDelay一">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-07-03T02:44:41.000Z">
<meta property="article:modified_time" content="2021-03-25T13:15:49.037Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="定时任务">
<meta property="article:tag" content="scheduled">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://littlefxc.github.io/2019/07/03/spring%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E8%AF%A6%E8%A7%A3%EF%BC%88-Scheduled%E6%B3%A8%E8%A7%A3%EF%BC%89/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>spring定时任务详解（@Scheduled注解） | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/blog/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/blog/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/blog/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/blog/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring-%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E8%AF%A6%E8%A7%A3%EF%BC%88-Scheduled%E6%B3%A8%E8%A7%A3%EF%BC%89"><span class="nav-text">Spring 定时任务详解（@Scheduled注解）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#cron%E8%A1%A8%E8%BE%BE%E5%BC%8F%E8%AF%A6%E8%A7%A3"><span class="nav-text">cron表达式详解</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">184</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">35</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/07/03/spring%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E8%AF%A6%E8%A7%A3%EF%BC%88-Scheduled%E6%B3%A8%E8%A7%A3%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          spring定时任务详解（@Scheduled注解）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-07-03 10:44:41" itemprop="dateCreated datePublished" datetime="2019-07-03T10:44:41+08:00">2019-07-03</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/blog/categories/spring/" itemprop="url" rel="index"><span itemprop="name">spring</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>[TOC]</p>
<h2 id="Spring-定时任务详解（-Scheduled注解）"><a href="#Spring-定时任务详解（-Scheduled注解）" class="headerlink" title="Spring 定时任务详解（@Scheduled注解）"></a>Spring 定时任务详解（@Scheduled注解）</h2><ol>
<li><p>initialDelay :初次执行任务之前需要等待的时间</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled(initialDelay =5000)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>fixedDelay:每次执行任务之后间隔多久再次执行该任务。(项目启动时，会立即执行任务。可以配合initialDelay一起使用（项目启动后延时执行任务）</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled(fixedDelay=5000)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// something that should execute periodically</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>fixedRate:执行频率，每隔多少时间就启动任务，不管该任务是否启动完成。(项目启动时，会立即执行任务。可以配合initialDelay一起使用（项目启动后延时执行任务）)</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled(fixedRate=5000)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>cron=”” 设置时分秒等具体的定时，网上很很多相关列子。</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scheduled(cron=&quot;*/5 * * * * MON-FRI&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doSomething</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// something that should execute on weekdays only</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> @Scheduled(cron = “10 0/10 *  * * ?”)</p>
</li>
</ol>
<h3 id="cron表达式详解"><a href="#cron表达式详解" class="headerlink" title="cron表达式详解"></a>cron表达式详解</h3><p>一个cron表达式有至少6个（也可能7个）有空格分隔的时间元素。按顺序依次为:</p>
<pre><code>1  秒（0~59）
2  分钟（0~59）
3  小时（0~23）
4  天（0~31）
5  月（0~11）
6  星期（1~7 1=SUN 或 SUN，MON，TUE，WED，THU，FRI，SAT）
7  年份（1970－2099）
</code></pre>
<p>其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通    配符。由于”月份中的日期”和”星期中的日期”这两个元素互斥的,必须要对其中一个设置?.</p>
<pre><code>&quot;0 0 10,14,16 * * ?&quot;       每天上午10点，下午2点，4点
&quot;0 0/30 9-17 * * ?&quot;         朝九晚五工作时间内每半小时
&quot;0 0 12 ? * WED&quot;            表示每个星期三中午12点
&quot;0 0 12 * * ?&quot;              每天中午12点触发
&quot;0 15 10 ? * *&quot;             每天上午10:15触发
&quot;0 15 10 * * ?&quot;             每天上午10:15触发
&quot;0 15 10 * * ? *&quot;           每天上午10:15触发
&quot;0 15 10 * * ? 2005&quot;        2005年的每天上午10:15触发
&quot;0 * 14 * * ?&quot;              在每天下午2点到下午2:59期间的每1分钟触发
&quot;0 0/5 14 * * ?&quot;            在每天下午2点到下午2:55期间的每5分钟触发
&quot;0 0/5 14,18 * * ?&quot;         在每天下午2点到2:55期间和下午6点到6:55期间的每5钟触发
&quot;0 0-5 14 * * ?&quot;            在每天下午2点到下午2:05期间的每1分钟触发
&quot;0 10,44 14 ? 3 WED&quot;        每年三月的星期三的下午2:10和2:44触发
&quot;0 15 10 ? * MON-FRI&quot;       周一至周五的上午10:15触发
&quot;0 15 10 15 * ?&quot;            每月15日上午10:15触发
&quot;0 15 10 L * ?&quot;             每月最后一日的上午10:15触发
&quot;0 15 10 ? * 6L&quot;            每月的最后一个星期五上午10:15触发
&quot;0 15 10 ? * 6L 2002-2005&quot;  2002年至2005年的每月的最后一个星期五上午10:15发
&quot;0 15 10 ? * 6#3&quot;           每月的第三个星期五上午10:15触发
</code></pre>
<p>有些子表达式能包含一些范围或列表</p>
<p>例如：</p>
<ol>
<li>子表达式（天（星期））可以为 <code>MON-FRI</code>, <code>MON,WED,FRI</code>, <code>MON-WED,SAT</code></li>
<li><code>*</code> 字符代表所有可能的值</li>
<li><code>/</code> 字符用来指定数值的增量</li>
</ol>
<p>例如：</p>
<ol>
<li><p>在子表达式（分钟）里的 <code>0/15</code> 表示从第0分钟开始，每15分钟</p>
</li>
<li><p>在子表达式（分钟）里的 <code>3/20</code> 表示从第3分钟开始，每20分钟（它和“3，23，43”）的含义一样</p>
</li>
<li><p><code>?</code> 字符仅被用于天（月）和天（星期）两个子表达式，表示不指定值。</p>
<p> 当2个子表达式其中之一被指定了值以后，为了避免冲突，需要将另一个子表达式的值设为 <code>?</code></p>
</li>
<li><p><code>L</code> 字符仅被用于天（月）和天（星期）两个子表达式，它是单词 <code>last</code> 的缩写</p>
</li>
<li><p>如果在 <code>L</code> 前有具体的内容，它就具有其他的含义了。例如：<code>6L</code> 表示这个月的倒数第 6 天</p>
</li>
<li><p>注意：在使用 <code>L</code> 参数时，不要指定列表或范围，因为这会导致问题</p>
</li>
<li><p>W 字符代表着平日(Mon-Fri)，并且仅能用于日域中。它用来指定离指定日的最近的一个平日。</p>
<p> 大部分的商业处理都是基于工作周的，所以 W 字符可能是非常重要的。<br> 例如，日域中的 15W 意味着 “离该月15号的最近一个平日。” 假如15号是星期六，那么 trigger 会在14号(星期五)触发，因为星期四比星期一离15号更近。</p>
</li>
<li><p>C：代表“Calendar”的意思。</p>
<p> 它的意思是计划所关联的日期，如果日期没有被关联，则相当于日历中所有日期。<br> 例如5C在日期字段中就相当于日历5日以后的第一天。1C在星期字段中相当于星期日后的第一天。</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>字段</th>
<th>允许值</th>
<th>允许的特殊字符</th>
</tr>
</thead>
<tbody><tr>
<td>秒</td>
<td>0-59</td>
<td>, - * /</td>
</tr>
<tr>
<td>分</td>
<td>0-59</td>
<td>, - * /</td>
</tr>
<tr>
<td>小时</td>
<td>0-23</td>
<td>, - * /</td>
</tr>
<tr>
<td>日期</td>
<td>1-31</td>
<td>, - * ? / L W C</td>
</tr>
<tr>
<td>月份</td>
<td>1-12 或者 JAN-DEC</td>
<td>, - * /</td>
</tr>
<tr>
<td>星期</td>
<td>1-7 或者 SUN-SAT</td>
<td>, - * ? / L C #</td>
</tr>
<tr>
<td>年（可选）</td>
<td>留空, 1970-2099</td>
<td>, - * /</td>
</tr>
</tbody></table>
<p>定时任务执行原理：<a target="_blank" rel="noopener" href="https://blog.csdn.net/gaodebao1/article/details/51789225">https://blog.csdn.net/gaodebao1/article/details/51789225</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1/" rel="tag"># 定时任务</a>
              <a href="/blog/tags/scheduled/" rel="tag"># scheduled</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/blog/2019/06/26/logback-Kafka-logstash%E9%9B%86%E6%88%90/" rel="prev" title="logback+Kafka+logstash集成">
                  <i class="fa fa-chevron-left"></i> logback+Kafka+logstash集成
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/blog/2019/07/22/redis%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84sortedset/" rel="next" title="redis数据结构sortedset">
                  redis数据结构sortedset <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/blog/js/utils.js"></script><script src="/blog/js/motion.js"></script><script src="/blog/js/schemes/muse.js"></script><script src="/blog/js/next-boot.js"></script>

  
<script src="/blog/js/local-search.js"></script>






  





</body>
</html>
